
package com.x52im.rbchat.logic.chat_root.face;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ImageSpan;

import com.x52im.rbchat.MyApplication;
import com.x52im.rbchat.logic.chat_root.model.FaceEntity;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EmojiUtil {

    private static Pattern eMojiPattern = Pattern.compile("\\[/\\w+\\]");

    public static Drawable getEmojiDrawableByDesc (Context context, String desc, int width, int height){
        Drawable drawable = getIEmojiDrawableByDesc(desc);
        Drawable newDrawable = null;
        // scale
        if (drawable != null) {
//            int width = (int) (drawable.getIntrinsicWidth() * scale);
//            int height = (int) (drawable.getIntrinsicHeight() * scale);
            Drawable.ConstantState cState = drawable.getConstantState();
            newDrawable = cState != null ? cState.newDrawable() : null;
            if(newDrawable != null)
                newDrawable.setBounds(0, 0, width, height);
        }
        return newDrawable;
    }

    private static Drawable getIEmojiDrawableByDesc(String desc) {
        if (TextUtils.isEmpty(desc)) return null;
        FaceEntity iEmoji = getIEmojiByDesc(desc);
        return iEmoji == null ? null : iEmoji.getImage();
    }

    public static FaceEntity getIEmojiByDesc(String desc){
        if (TextUtils.isEmpty(desc)) return null;
        ArrayList<FaceEntity> faces = MyApplication.getInstance2().getIMClientManager().getFaceDataProvider().getFaceDatas();
        for(FaceEntity face : faces){
            if(desc.equals(face.getDesc())){
                return face;
            }
        }
        return null;
    }

    /**
     * 将可能含有表情描述符的字符串转换为SpannableString
     * @param context
     * @param value 可能含有表情描述符（形如[/流汗]）的字符串
     * @param width
     * @param height
     * @param align
     * @return SpannableString
     */
    public static SpannableString replaceEmoticons(Context context, String value, int width, int height, int align) {
        if (TextUtils.isEmpty(value)) {
            value = "";
        }

        SpannableString mSpannableString = new SpannableString(value);
        Matcher matcher = eMojiPattern.matcher(value);
        while (matcher.find()) {
            int start = matcher.start();
            int end = matcher.end();
            String emot = value.substring(start, end);
            Drawable d =  getEmojiDrawableByDesc(context, emot, width, height);
            if (d != null) {
                ImageSpan span = new ImageSpan(d, align);
                mSpannableString.setSpan(span, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        return mSpannableString;
    }

}
